// pages/subscribe/subscribe.js
let app = getApp()
let request = require('../../utils/request')
let addFlag = false
var timestampTool = require('../../utils/time.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    pageAllHeight: app.globalData.pageAllHeight,
    screenHeight: 0,
    parkId: 0,
    parkInfo: {},
    subscribeRule: [],
    timeTab: [],
    timeTabIndex: 0,
    timeTabArrObject: [],
    timeListArr: ['0:00-1:00','1:00-2:00', '2:00-3:00', '3:00-4:00', '4:00-5:00', '5:00-6:00', '6:00-7:00', '7:00-8:00', '8:00-9:00', '9:00-10:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00', '22:00-23:00', '23:00-24:00'],
    timeList: [],
    timeListIndex: -1,
    carNumList: [],
    carNumberIndex: 0,
    payMoney: 0,
    haveApplyList: [],
    longitude: 0,
    latitude: 0,
    searchDialog: false,
    searchResult: [],
    searcheVip: [],
    addCarDialog: false,
    activeIptIndex: -1,
    carNo: '',
    inputLen: 8,
    orderTime:60,
    orderTimeState:false,
    setIntervalTime:'',
    showCarMoney:true,
    hiddenReserveMoney:true,
    hiddenDesc:false,
    parkingNumber:'',
    startTimesss:'',
    endsTime:'',
    authorizationPhone: false,
    code:'',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log('参数：', options)
    let homeSbuBtn = options.homeSbuBtn ? JSON.parse(options.homeSbuBtn) : false
    this.setData({
      parkId: options.parkId,
      homeSbuBtn: homeSbuBtn,
      parkInfo: {
        parkName: options.parkName,
        reserveParkSpace: options.reserveParkSpace
      },
      screenHeight: wx.getSystemInfoSync().screenHeight
    })
    wx.login({  //先登录提前保存code
      success: res => {
        this.setData({
          code: res.code
        })
      }
    });
    if (homeSbuBtn == true) {
      //  获取当前位置
      this.getUserLocation()
    } else {
      //  获取停车场预约收费规则
      this.getSubscribeRule()
      //  已预约车辆
      this.getHaveApply()
    }
    //  设置时间切换栏
    this.setTimeBar()
    //  查询车牌列表
    this.getCarNumList()
    //  设置时间列表
    this.setTimeList()


    
    
    
  },
  onShow () {
    // this.showcarPlateNumber()
  },
  /**
 * 获取用户当前位置
 */
  getUserLocation() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        let longitude = res.longitude;
        let latitude = res.latitude;
        that.setData({ longitude, latitude });
        //  附近有月租规则停车场
        that.getRecentlySubscribe()
      }
    })
  },
  /**
   * 附近有月租规则停车场
   */
  getRecentlySubscribe() {
    let that = this
    let parmas = {
      latitude: this.data.latitude,
      longitude: this.data.longitude
    }
    request.http('/park/info/getNearbyReserveParkList', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            parkId: data.data.id,
            'parkInfo.parkName': data.data.parkName
          })
          //  获取停车场预约收费规则
          that.getSubscribeRule()
          //  已预约车辆
          that.getHaveApply()
        }
      })
  },
  /**
   * 打开搜索弹窗
   */
  showSearchDialog() {
    this.setData({
      searchDialog: true,
      searcheVip: wx.getStorageSync('lmtc_searcheSubscribe')
    })
  },
  /**
  * 关闭搜索弹窗
  */
  hiddenSearchDialog() {
    this.setData({
      searchDialog: false
    })
  },
  /**
   * 获取搜索框内容
   */
  getSearch(e) {
    let that = this
    let val = e.detail.value
    this.setData({
      searchAddress: val
    })
    let parmas = {
      keyword: val
    }
    request.http('/park/info/getParkByName', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            searchResult: data.data
          })
        }
      })
  },
  /**
   * 点击搜索到的停车场事件
   */
  selectPark(e) {
    let index = e.currentTarget.dataset.index
    let searchResult = this.data.searchResult
    let record = {
      parkName: searchResult[index].parkName,
      address: searchResult[index].parkAddress,
      id: searchResult[index].id
    }
    this.setData({
      parkId: searchResult[index].id,
      'parkInfo.parkName': searchResult[index].parkName,
      searchDialog: false
    })
    let searcheSubscribe = wx.getStorageSync('lmtc_searcheSubscribe');
    if (Array.isArray(searcheSubscribe)) {
      if (searcheSubscribe.length == 2) {
        searcheSubscribe.splice(1, 1);
        searcheSubscribe.unshift(record);
      } else {
        searcheSubscribe.unshift(record);
      }
    } else {
      searcheSubscribe = [];
      searcheSubscribe.push(record);
    }
    wx.setStorageSync('lmtc_searcheSubscribe', searcheSubscribe);
    //  获取停车场预约收费规则
    this.getSubscribeRule()
    //  已预约车辆
    this.getHaveApply()
  },
  /**
   * 点击历史搜索记录
   */
  selectSearchPark(e) {
    let searcheVip = this.data.searcheVip
    let index = e.currentTarget.dataset.index
    console.log('搜索停车场：', searcheVip)
    this.setData({
      parkId: searcheVip[index].id,
      'parkInfo.parkName': searcheVip[index].parkName,
      searchDialog: false
    })
    //  获取停车场预约收费规则
    this.getSubscribeRule()
    //  已预约车辆
    this.getHaveApply()
  },
  /**
   * 获取停车场预约剩余车位
   */
  getParkingApplyNumber(index) {
    let that = this
    let timeTabArrObject = that.data.timeTabArrObject
    let date = new Date()
    let year = date.getFullYear()
    index = index ? index : this.data.timeTabIndex
    let startTime = this.data.timeTab[index]
    startTime = startTime.split('.')
    let parmas = {
      parkId: this.data.parkId,
      reserveDate: year + '-' + startTime[0] + '-' + startTime[1]
    }
    request.http('/park/info/getParkReservesSpace', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          if (data.data == 0) {
            for (var i = 0; i < timeTabArrObject.length; i++) {
              if (timeTabArrObject[i].date == parmas.reserveDate) {
                timeTabArrObject[i].forbidden = true
              }
            }
          }
          that.setData({
            'parkInfo.reserveParkSpace': data.data,
            timeTabArrObject
          })
        }
      })
  },
  /**
   * 获取停车场预约收费规则
   */
  getSubscribeRule() {
    request.http('/promotion/reserve-fee-scale/getMonthRulePaytypeByParkId', 'GET', { parkId: this.data.parkId })
      .then(res => {
        console.log(res.data);
        let data = res.data
        if (data.code == 200) {
          let subscribeRule = data.data
          for (var i = 0; i < subscribeRule.length; i++) {
            var reserveBeginTime = subscribeRule[i].reserveBeginTime
            var reserveEndTime = subscribeRule[i].reserveEndTime
            subscribeRule[i].reserveBeginTime = reserveBeginTime.substring(0, 5)
            subscribeRule[i].reserveEndTime = reserveEndTime.substring(0, 5)
          }

          // 监听页面加载，如果金额为0 则隐藏
          if( res.data.data[0].amount == 0 ){
            console.log('预约费为0');
            this.setData({
              showCarMoney:false,
              hiddenReserveMoney:false,
              hiddenDesc:true
            })
          }
          this.setData({
            subscribeRule
          })
          //计算时间  查出收费规则
          let date = new Date();
          let endTime = date.getHours()+1 == 24?'00':date.getHours()+1;
          if (endTime < '11:00') {
            this.setData({
              payMoney: this.data.subscribeRule[0].amount
            })
          } else {
            this.setData({
              payMoney: this.data.subscribeRule[1].amount
            })
          }        
        }
      })
  },
  // 已预约车辆
  getHaveApply() {
    let that = this
    request.http('/order-reserve/park-reserve-record/get-unfinished-by-parkid', 'GET', { parkId: this.data.parkId })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            haveApplyList: data.data
          })
        }
      })
  },
  /**
   * 设置时间切换栏
   */
  setTimeBar() {
    let date = new Date()
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let timeTab = this.data.timeTab
    let timeTabArrObject = this.data.timeTabArrObject
    timeTabArrObject.push({ date: year + '-' + month + '-' + day, forbidden: false })
    timeTab.push(month + '.' + day)
    for (var i = 0; i < 1; i++) {
      day += 1
      if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        if (day > 31) {
          month += 1
          day = 1
        }
      } else if (month == 4 || month == 6 || month == 9 || month == 11) {
        if (day > 30) {
          month += 1
          day = 1
        }
      } else if (month == 2) {
        if (year % 4 == 0) {
          if (day > 29) {
            month += 1
            day = 1
          }
        } else {
          if (day > 28) {
            month += 1
            day = 1
          }
        }
      }
      if (month > 12) {
        month = 1
      }
      timeTab.push(month + '.' + day);
      timeTabArrObject.push({ date: year + '-' + month + '-' + day, forbidden: false })
    }
    this.setData({
      timeTab,
      timeTabArrObject
    })
    // for (var i = 0; i < timeTab.length; i++) {
    //   this.getParkingApplyNumber(i)
    // }
  },
  /**
   * 设置时间列表
   */
  setTimeList() {
    let date = new Date()
    let hour = date.getHours() + ''
    hour = hour.length < 2 ? '0' + hour : hour
    let month = date.getMinutes() + ''
    month = month.length < 2 ? '0' + month : month
    let timeList = this.data.timeListArr
    let newTimeList = []
    for (var i = 0; i < timeList.length; i++) {
      var time = timeList[i].split('-')
      time[0] = time[0].length < 5 ? '0' + time[0] : time[0]
      if ((time[0] < hour + ':' + month) && this.data.timeTabIndex == 0) {
        newTimeList.push({ forbidden: true, time: timeList[i] })
      } else {
        newTimeList.push({ forbidden: false, time: timeList[i] })
      }
    }
    this.setData({
      timeList: newTimeList
    })
  },
  /**
   * 选择tab
   */
  selectBar(e) {
    let index = e.target.dataset.index
    if (this.data.timeTabIndex == index) {
      return
    }
    this.setData({
      timeTabIndex: index,
      timeListIndex: -1,
      payMoney: 0
    })
    //  设置时间列表
    this.setTimeList()
    //  获取停车场预约剩余车位
    this.getParkingApplyNumber()
  },
  /**
   * 选择时间
   */
  selectTime(e) {
    let date = new Date()
    let hour = date.getHours() + ''
    hour = hour.length < 2 ? '0' + hour : hour
    let month = date.getMinutes() + ''
    month = month.length < 2 ? '0' + month : month
    let index = e.target.dataset.index
    let timeList = this.data.timeListArr
    var time = timeList[index].split('-')
    if (this.data.timeListIndex == index) {
      return
    }
    time[0] = time[0].length < 5 ? '0' + time[0] : time[0]
    if (time[0] < '11:00') {
      this.setData({
        payMoney: this.data.subscribeRule[0].amount
      })
    } else {
      this.setData({
        payMoney: this.data.subscribeRule[1].amount
      })
    }
    this.setData({
      timeListIndex: index
    })
  },
  /**
  * 查询车牌列表
  */
  getCarNumList() {
    let that = this;
    let url = "/customer/car/getCustomerCarList";
    request.http(url, 'GET')
      .then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          let list = res.data.data;
          if (list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              if (i == 0) {
                list[i]['select'] = true
              } else {
                list[i]['select'] = false
              }
            }
            that.setData({
              carNumList: list
            })
          } else {
            that.setData({
              carNumList: []
            })
          }
        }
      })
  },

  // 弹窗，查看是否有车牌信息，有--弹窗
  async showcarPlateNumber () {
    let url = "/customer/car/getCustomerCarList";
    const { data : res } = await request.http(url, 'GET')
    console.log(res.data);
      if (res.data.length == 0 ) {
        this.setData({
          addCarDialog: true
        })
      }else{
        this.setData({
          addCarDialog: false
        })
      }
  },
  /**
   * 选择车牌号
   */
  selectCar(e) {
    let index = e.currentTarget.dataset.index
    let carList = this.data.carNumList
    for (var i = 0; i < carList.length; i++) {
      carList[i]['select'] = false
    }
    carList[index]['select'] = true
    this.setData({
      carNumList: carList,
      carNumberIndex: index
    })
  },
  // 显示添加车牌号弹窗
  showAddCarDialog() {
    this.setData({
      addCarDialog: true
    })
  },
  /**
   * 隐藏添加车牌号弹窗
   */
  diddenAddCarDialog() {
    this.setData({
      addCarDialog: false
    })
  },
  /**
  * 输入车牌号
  */
  onFocus: function (e) {
    var that = this;
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(that.data.carNo)) {
      inputType = 2;
    }
    that.setData({
      showPlateInput: true,
      inputType: inputType,
      activeIptIndex: that.data.carNo.length
    });
  },
  /**
   * 键盘输入操作
   */
  handlePlateChange(e) {
    let value = e.detail.value;
    let inputLen = this.data.inputLen;
    let type = e.detail.type;
    let carNo = this.data.carNo;
    if (carNo.length < inputLen) {
      carNo += value;
    }
    if (type == 1) {
      this.setData({
        inputType: 2
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
   * 用于点击弹出键盘输入，space为键盘弹出后向上拉取的距离 
   * @param {*} e 
   */
  handleClick(e) {
    /* 150为键盘的高度 */
    let space = -(e.currentTarget.offsetTop - 150);
    /* regExp用于判断当前已输入的车牌号是否是中文，并让键盘显示中文还是英文输入 */
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(this.data.carNo)) {
      inputType = 2;
    }
    this.setData({
      translateSpace: space,
      showPlateInput: true,
      inputType
    })
  },
  /**
   * 键盘隐藏事件
   */
  handleHiddenCarPlate() {
    this.setData({
      showPlateInput: false,
      activeIptIndex: -1
    })
  },
  /**
   * 点击键盘上的确定
   */
  handlePlateConfirm() {
    /* isCarPlate用于判断输入的车牌号是否符合规范 */
    if (!this.isCarPlate(this.data.carNo)) {
      wx.showToast({
        title: '请输入正确车牌号',
        icon: 'none'
      })
      return false;
    }
    this.setData({
      translateSpace: 0,
      showPlateInput: false,
      inputType: 1,
      activeIptIndex: -1
    })
  },
  /**
   * 用于键盘输入删除
   */
  handlePlateDelete(e) {
    let carNo = this.data.carNo;
    carNo = carNo.substring(0, carNo.length - 1);
    if (carNo.length == 0) {
      this.setData({
        inputType: 1
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
  * 判断车牌号
  * @param {String} value 车牌号
  */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /**
   * 添加车牌号
   */
  addCarNumber() {
    if (addFlag) {
      return
    }
    let that = this;
    let carNo = that.data.carNo;
    if (!that.isCarPlate(that.data.carNo)) {
      wx.showToast({
        title: '请输入正确车牌号',
        icon: 'none'
      })
      return;
    }
    addFlag = true
    let url = '/customer/car/addCustomerCar'
    let params = {
      carNumber: carNo
    }
    request.http(url, 'POST', params)
      .then((res) => {
        let data = res.data
        if (data.code == 200) {
          console.log(data);
          wx.showToast({ title: '添加成功' })
          that.setData({ carNo: '' })
          that.getCarNumList();
          that.handleHiddenCarPlate()
          that.diddenAddCarDialog()
        } else {
          // wx.showToast({ title: '添加失败，请稍后重试！', icon: 'none' })
        }
        addFlag = false
      }).catch((errMsg) => {
        addFlag = false
      });
  },

  // 支付预约
  toPay() {
    let that = this;
    let date = new Date()
    let year = date.getFullYear()
    let dateTime = year + '-' + this.data.timeTab[this.data.timeTabIndex].split('.')[0] + '-' + this.data.timeTab[this.data.timeTabIndex].split('.')[1];
    let carNumber = this.data.carNumList.length != 0? this.data.carNumList[this.data.carNumberIndex].carNumber : null;
    let phoneNumber = wx.getStorageSync("phoneNumber");
    if (phoneNumber == '' || phoneNumber == undefined || phoneNumber == null) {
      this.setData({ authorizationPhone: true })
      return false
    }
    if (!carNumber) {
      wx.showToast({
        title: '未选择入场车牌',
        icon: 'none'
      })
      return false
    }
    let parkId = this.data.parkId
    //计算时间  在查出收费规则
    let startTime = date.getHours()
    let starMinutes = date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes();
    let startTimesss = `${dateTime} ${startTime}:${starMinutes}:00`;
    this.setData({ startTimesss })

    // 根据时间计算收费
    let currentHour = date.getHours()+1 == 24?'00':date.getHours()+1;
    if (currentHour < '11:00') {
      this.setData({
        payMoney: this.data.subscribeRule[0].amount
      })
    } else {
      this.setData({
        payMoney: this.data.subscribeRule[1].amount
      })
    }
    let price = this.data.payMoney;
    if (price == 0){
      let parmas = {
        carNumber: carNumber,
        parkId: parkId,
        reserveAmount: price,
      }
      request.http('/order-reserve/park-reserve-record/reserve-no-pay', 'POST', parmas,0)
        .then(res => {
          let data = res.data
          if (data.code == 200) {
            wx.showToast({
              title: '预约成功',
              success(res) {
                wx.redirectTo({
                  url: '/pages/freeRecardList/freeRecardList',
                })
              }
            })
          }
        })
    }else{
      // 预约费不为0
      let beginTime = this.data.startTimesss
      let timestamp1 = Date.parse(new Date(beginTime))/1000; 
      let switchTime = timestampTool.formatTime(timestamp1, 'Y-M-D h:m:s')
      console.log('开始时间',switchTime); 
      let timestamp2 = timestamp1 + 30 * 60 
      timestamp2 = timestampTool.formatTime(timestamp2, 'Y-M-D h:m:s')
      console.log('结束时间',timestamp2);

      let parmas = {
        carNumber: carNumber,
        parkId: parkId,
        reserveAmount: price,
      }
      request.http('/order-reserve/park-reserve-record/reserve', 'POST',parmas,0)
        .then(res => {
          console.log(res);
          let data = res.data
          if (data.code == 200) {
            //预约中一分钟之内支付
            that.closeOrderTime()
            wx.requestPayment({
              timeStamp: data.data.timeStamp, // 时间戳，必填（后台传回）
              nonceStr: data.data.nonceStr, // 随机字符串，必填（后台传回）
              package: data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
              signType: data.data.signType, // 签名算法，非必填，（预先约定或者后台传回）
              paySign: data.data.paySign, // 签名 ，必填 （后台传回）
              success: function (res) { // 成功后的回调函数
                console.log(res);
                // 支付成功预约费后查询车位，开始时间，结束时间
               request.http('/order-reserve/park-reserve-record/get-reserve-space-code','GET',parmas,0)
                .then( res => {
                console.log(res.data);
                if(res.data.code==200){
                  let parkingNumber = res.data.data.spaceCode
                  let reserveEndTime = res.data.data.reserveEndTime
                  if(parkingNumber != null && reserveEndTime != null) {
                    console.log('有时间');
                    wx.showModal({
                      title: "预约成功",
                      content:`预约车位为${parkingNumber}\r\n请于${reserveEndTime}之前入场`,
                      success: function (res) {
                        if (res.confirm) {
                          wx.redirectTo({
                            url: '/pages/applayRecord/applayRecord',
                          })
                        } else {
                          console.log('取消')
                        }
                      }
                    })
                  }else {
                    console.log('时间为空');
                    wx.showModal({
                      title: "预约成功",
                      content:`请于半小时之内进入预约车位`,
                      success: function (res) {
                        if (res.confirm) {
                          wx.redirectTo({
                            url: '/pages/applayRecord/applayRecord',
                          })
                        } else {
                          console.log('取消')
                        }
                      }
                    })
                  }

                }
              })
              clearInterval(that.data.setIntervalTime)
              that.setData({
                orderTimeState :false
              })
              },
              fail(res) {
                // Toast.fail('支付失败');
                if(res.errMsg == "requestPayment:fail cancel"){
                  wx.showModal({
                    title:"提示",
                    content:"支付失败,请重新预约"
                  })
                  clearInterval(that.data.setIntervalTime)
                  that.setData({
                    orderTimeState :false
                  })
                  that.payFailure(data.data.orderCode)     //订单号传给后台，支付失败   关闭订单
                }
              }
            })
          }
        })
    }
  },

  //支付失败 ， 调取接口后台预约占车位+1
  payFailure(code){
    request.http('/order-reserve/park-reserve-record/close-pay', 'POST',{orderCode:code})
    .then(res => {
      let data = res.data
      if (data.code == 200) {
        console.log(data)
      }
    })
  },


  // 倒计时
  closeOrderTime(){
    let orderTime = 60;
    let that = this;
    this.data.setIntervalTime = setInterval(function(){
      orderTime --
      if(orderTime == 0){
        clearInterval(that.data.setIntervalTime)
        that.setData({
          orderTime : 0,
          orderTimeState:false
        })
      }
      that.setData({
        orderTime : orderTime,
        orderTimeState :true
      })
    },1000)
  }
})